package com.hardydou.framework.websocket;

import cn.hutool.json.JSONUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.hardydou.common.result.Result;
import com.hardydou.common.result.ResultHelper;
import com.hardydou.framework.websocket.service.WsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;

/**
 * @author ：hardy
 * @description：
 * @date ：Created in 2020/7/1
 * @Copyright ：Hardydou.com
 */
@ServerEndpoint("/wss/{userId}")
@Component
public class WsServer {
    static Log log = LogFactory.get(WsServer.class);
    IWsService wsService = new WsServiceImpl();

    @OnOpen
    public void onOpen(Session session, @PathParam("userId") Long userId) {
        Result result = ResultHelper.ok();
        UserSession userSession = new UserSession(userId, session);
        try {
            wsService.add(userSession);
            session.getBasicRemote().sendText(JSONUtil.toJsonStr(result));
        } catch (IOException e) {
            log.error("网络异常（{}） ", userId);
            wsService.remove(userSession);
        }
    }

    @OnClose
    public void onClose(Session session) {
        UserSession userSession = wsService.findBySid(session.getId());
        wsService.remove(userSession);
        log.info("用户退出({})", userSession.getUserId());
    }

    /***
     * message格式:<br/>
     * {
     *     toUserId: int,
     *     type:'TXT'|'BYTE',
     *     textData:'消息内容',
     *     byteData:xxxxx,
     * }
     * @param message
     * @param session
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        WsMessage wsMessage = JSONUtil.toBean(message, WsMessage.class);
        UserSession userSession = wsService.findBySid(session.getId());
        wsMessage.setFromUserId(userSession.getUserId());
        wsService.accept(wsMessage);
    }

    @OnError
    public void onError(Session session, Throwable error) {
        UserSession userSession = wsService.findBySid(session.getId());
        log.error(error, "用户错误({}),{}", userSession.getUserId(), error.getMessage());
        wsService.remove(userSession);
    }
}
